﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Shop4Aggies.Data_Access;
using System.Web.Security;

namespace Shop4Aggies
{
    public partial class AddProduct : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
            {
                Response.Redirect("Account/Login.aspx?ReturnUrl=~/AddProduct.aspx");
            }
        }

        private string ImageName
        {
            get 
            {
                return HiddenImgName.Value;
            }
            set 
            {
                HiddenImgName.Value = value;
                ImgPreview.ImageUrl = "~/Catalog/Images/" + HiddenImgName.Value;
            }
        }

        private string[] acceptableFiles = new string[]
        {
            ".png",
            ".jpg",
            ".gif",
            ".bmp",
            ".jpeg",
            ".tif",
            ".tiff"
        };

        protected void BtnImageUpload_Click(object sender, EventArgs e)
        {
            ErrorUpload.Text = "";

            if (ImageUpload.HasFile)
            {
                string strFile = ImageUpload.FileName;

                bool bOkayToLoad = false;
                string strExtension = "";

                //check to be certain this is image file
                foreach (string s in acceptableFiles)
                {
                    if (strFile.EndsWith(s, StringComparison.InvariantCultureIgnoreCase))
                    {
                        bOkayToLoad = true;
                        strExtension = s;
                    }
                }

                if (bOkayToLoad)
                {
                    SaveUploadPic(strExtension);
                }
                else
                {
                    ErrorUpload.Text = "File type not supported";
                }
            }
            else
            {
                ErrorUpload.Text = "No file selected";
            }
        }

        private void SaveUploadPic(string strExtension)
        {
            if (ImageUpload.HasFile)
            {
                try
                {
                    //save the image to the server
                    string nonce = Guid.NewGuid().ToString();
                    string filename = nonce + strExtension;
                    ImageUpload.SaveAs(Server.MapPath("/") + "Catalog\\Images\\" + filename);

                    //update the preview
                    ImageName = filename;
                }
                catch
                {
                    ErrorUpload.Text = "Error uploading file";
                }
            }
        }

        private bool ValidateValues()
        {
            bool bValid = true;

            ErrorName.Text = "";
            ErrorUpload.Text = "";
            ErrorPrice.Text = "";

            if (string.IsNullOrWhiteSpace(ProductName.Text))
            {
                bValid = false;
                ErrorName.Text = "Product name must be specified";
            }

            decimal dTrash;

            if (string.IsNullOrWhiteSpace(UnitPrice.Text))
            {
                bValid = false;
                ErrorPrice.Text = "Product price must be specified";
            }
            else if (!decimal.TryParse(UnitPrice.Text, out dTrash))
            {
                bValid = false;
                ErrorPrice.Text = "Incorrect price format";
            }

            return bValid;
        }

        protected void BtnAddProduct_Click(object sender, EventArgs e)
        {
            if (ValidateValues())
            {
                int productId;

                string imgName = ImageName;
                using (CommerceEntities db = new CommerceEntities())
                {
                    try
                    {
                        MembershipUser mu = Membership.GetUser();
                        string userID = mu.ProviderUserKey.ToString();

                        Product newProduct = new Product()
                        {
                            CategoryID = int.Parse(Category.SelectedValue),
                            ModelName = HttpUtility.HtmlEncode(ProductName.Text),
                            Description = HttpUtility.HtmlEncode(Description.Text),
                            UnitCost = decimal.Parse(UnitPrice.Text),
                            ProductImage = HttpUtility.HtmlEncode(imgName),
                            VendorID = userID
                        };
                        db.Products.AddObject(newProduct);
                        db.SaveChanges();

                        productId = newProduct.ProductID;
                    }
                    catch (Exception exp)
                    {
                        throw new Exception("ERROR: Unable to add product - " + exp.Message.ToString(), exp);
                    }
                }
                Response.Redirect("ProductDetails.aspx?ProductID=" + productId);
            }
        }
    }
}